import React, { PropsWithChildren } from "react";
import { Form, message } from "antd";
import { ModalForm, ProFormText } from "@ant-design/pro-components";
import { adminV1AdminControllerUpdateMine } from "@/services/auto/adminAdmin";

interface FormData extends Pick<API.AdminUpdateDto, 'password'> {
  oldPassword: string;
}

export default function UpdatePassword(props: PropsWithChildren){
  const { children } = props;

  const [form] = Form.useForm<FormData>();

  return (
    <ModalForm
      layout="horizontal"
      width={400}
      labelCol={{style: {width: 100}}}
      modalProps={{
        maskClosable: false,
      }}
      form={form}
      onOpenChange={(val) => {
        if (!val) {
          form.resetFields();
        }
      }}
      title={'修改密码'}
      trigger={children as JSX.Element}
      onFinish={(val) => {
        return adminV1AdminControllerUpdateMine({
          password: val.password,
          oldPassword: val.oldPassword,
        })
          .then(() => {
            message.success('操作成功');
            return true;
          })
          .catch(() => {
            return false;
          });
      }}
    >
      <ProFormText.Password
        name="oldPassword"
        label="原密码"
        rules={[{ required: true, message: '请输入 原密码' }]}
        fieldProps={{
          maxLength: 50,
        }}
      />
      <ProFormText.Password
        name="password"
        label="新密码"
        rules={[{ required: true, message: '请输入 原密码' }]}
        fieldProps={{
          maxLength: 50,
          autoComplete: 'new-password',
        }}
      />
      <ProFormText.Password
        name="password2"
        label="确认新密码"
        required
        rules={[
          (form)=>{
            const password = form.getFieldValue('password');
            return {
              validator: (_,val)=>{
                if(!val){
                  return Promise.reject('请输入 确认新密码')
                }
                if(val !== password){
                  return Promise.reject('两次密码不一致')
                }
                return  Promise.resolve();
              },
            }
          }
        ]}
        fieldProps={{
          maxLength: 50,
          autoComplete: 'new-password',
        }}
      />
    </ModalForm>
  );

}
